<?php 
session_start();
define("CCTRL", "sendmail");
define("CCTRLNAME", "sendmail");
class sendmail extends CI_Controller  {
        /**
        * Index Page for this controller.
        *
        * Maps to the following URL
        * 		http://example.com/index.php/welcome
        *	- or -  
        * 		http://example.com/index.php/welcome/index
        *	- or -
        * Since this controller is set as the default controller in 
        * config/routes.php, it's displayed at http://example.com/
        *
        * So any other public methods not prefixed with an underscore will
        * map to /index.php/welcome/<method_name>
        * @see http://codeigniter.com/user_guide/general/urls.html
        */
       private $_configs = null;
       function __construct()
        {
            parent::__construct();
            include APPPATH . 'libraries/defu.php';
            $this->load->helper('url');
            $this->load->library('smarty3','','smarty');
            $this->load->model('APanel/product_model');
            $this->load->model('APanel/customer_model');
            $this->load->model('APanel/type_model');
            require( APPPATH . 'libraries/phpmailer/class.phpmailer.php');
            $this->product_model=new product_model();
            $this->customer_model=new customer_model();
            $this->type_model=new type_model();
        }
        public function index()
	{
            if(!checkAuthority(CCTRLNAME)){
                $this->smarty
                        ->assign('_SESSION', $_SESSION)
                        ->display("sys/04_access_denied");
                return;
            }
            $Data=null;
            $tmp=$this->type_model->getByType("Group");
            $Data["Group"]=$tmp;
            $this->smarty
                    ->assign('_SESSION', $_SESSION)
                    ->assign('Data', $Data)
                    ->display("APanel/sendmail/sendmail");
            
	}
        function Preview(){
            $Products=$this->input->post('products', TRUE);
            if(!$Products){ echo "Vui lòng chọn sản phẩm";return; }
            foreach ($Products as $p){
                $list[]=$p["ProductID"];
            }
            $mailBody=$this->CreateMailContent($list);
            echo $mailBody;
        }
        function tokenProduct(){
            $q=$_POST["q"];
            $this->load->model('admin-planners/product_model','product_model');
            $arr= ($this->product_model->getProductToken($q));
            $json_response = json_encode($arr);
            if(isset($_GET["callback"])) {
                $json_response = $_GET["callback"] . "(" . $json_response . ")";
            }
            echo $json_response;
        }
        function getCustomerByGroup(){
            $group=$this->input->post('Group', FALSE);
            //if(!$group){ echo "Vui lòng chọn Nhóm khách hàng.";return; }
            
            $cuslist=$this->customer_model->getByGroup($group);
            $Data["mailList"]=array();
            foreach ($cuslist as $cus){
                if((preg_match("/^[0-9a-zA-Z]\w+(\.\w+)*\@\w+(\.[0-9a-zA-Z]+)*\.[a-zA-Z]{2,4}$/", $cus->Email) === 0)){
                }else{
                    $Data["mailList"][]=$cus;
                }
            }
            $this->smarty->assign('Data',$Data );
            $this->smarty->display('APanel/sendmail/02_list');
        }
        function TestMail(){
            $Subject=$this->input->post('Subject', TRUE);
            $Email=$this->input->post('Email', TRUE);
            if((preg_match("/^[0-9a-zA-Z]\w+(\.\w+)*\@\w+(\.[0-9a-zA-Z]+)*\.[a-zA-Z]{2,4}$/", $Email) === 0)){
                $msgs[]="Email không hợp lệ. Email phải đúng định dạng [0-9a-z._]@[a-z].[a-z].";
            }
            if(!$Subject){ 
                $msgs[]="Bạn chưa nhập tiêu đề thư [Subject].";
            }
            $Products=$this->input->post('Products', TRUE);
            if(!$Products){ 
                $msgs[]="Bạn chưa chọn sản Phẩm nào. Hãy chọn một vài sản phẩm cần đính kèm thư.";
            }
            if(count($msgs)>0){
                $code=-999;
                $msg="";
                foreach ($msgs as $m){
                    $msg.="$m<br/>";
                }
            }else{
                foreach ($Products as $p){
                    $list[]=$p["ProductID"];
                }
                $Body=$this->CreateMailContent($list);
                if(!checkAuthority(CCTRL,false)){
                    $code=-1;
                    $msg="[Access Denied] Bạn không có quyền thực hiện thao tác này.<br/> Mọi thay đổi dữ liệu đều không được công nhận.";
                    echo json_encode(array("code"=>$code,"msg"=>$msg));return;
                }elseif($this->MailerTo($Email,$Email, $Subject, $Body)){
                    $code=1;
                    $msg="[Success] Gửi thành công. Vui lòng kiểm tra hộp thư đến.";
                }else{
                    $code=-1;
                    $msg="[Fail] Gửi thất bại.";
                }
            }
            echo json_encode(array("code"=>$code,"msg"=>$msg));
        }
        Private function MailerTo($sEmail,$sName,$sSubject="",$sBody=""){
            //$sEmail = ' khuongxuantruong@gmail.com '; // dia chi email se nhan mail 
            //$sName = 'KXT';// ten nguoi nhan
            $sEmailSender = 'noreply@dealgiadung.com';// dia chi email cua nguoi goi 
            $sSenderName ='Dealgiadung'; // Tên Người Gửi
            $sHost ='mail.dealgiadung.com'; //Host
            $sUser ='noreply@dealgiadung.com';// Tài Khoản Người gửi
            $sPass ='b0c057f0a715e648ac5dba9acf9c0ea6@THAILONG';// Mật Khẩu Tài Khoản Email
            //$sSubject =$sSubject; //Tiêu Đề Email
            //$sBody = $sBody; //Nội Dung Thư
            $mail = new PHPMailer();
            $mail->CharSet="utf-8";
            $mail->IsSMTP(); 
            $mail->Host = $sHost ; 
            $mail->Port="26";
            $mail->SMTPAuth = true; 
            $mail->Username = $sUser ; 
            $mail->Password = $sPass; 
            $mail->From = $sEmailSender;//$sEmailSender; 
            $mail->FromName = $sSenderName;//$sSenderName; 
            $mail->AddAddress($sEmail,$sName); 
            //$mail->AddReplyTo($sEmailSender,$sSenderName); 
            $mail->WordWrap = 50; 
            $mail->IsHTML(true); 
            $mail->Subject = $sSubject; 
            $mail->Body = $sBody; 
            $mail->AltBody = ""; 
            if(!$mail->Send()){ 
                //print $mail->ErrorInfo; 
                return false;
            }else{ 
                return true;
            }
        }
        function SendMail(){
            $Subject=$this->input->post('Subject', TRUE);
            $Products=$this->input->post('Products', TRUE);
            $Group=$this->input->post('Group', TRUE);
            if(!$Subject){ 
                $msgs[]="Bạn chưa nhập tiêu đề thư [Subject].";
            }
            if(!$Products){ 
                $msgs[]="Bạn chưa chọn sản Phẩm nào. Hãy chọn một vài sản phẩm cần đính kèm thư.";
            }
            if(count($msgs)>0){
                $code=-999;
                $msg="";
                foreach ($msgs as $m){
                    $msg.="$m<br/>";
                }
            }elseif(!checkAuthority(CCTRL,false)){
                $code=-1;
                $msg="[Access Denied] Bạn không có quyền thực hiện thao tác này.<br/> Mọi thay đổi dữ liệu đều không được công nhận.";
                echo json_encode(array("code"=>$code,"msg"=>$msg));return;
            }else{
                foreach ($Products as $p){
                    $list[]=$p["ProductID"];
                }
                $Body=$this->CreateMailContent($list);
                $oCuslist=$this->customer_model->getByGroup($Group);
                $nCus=count($oCuslist);
                if(count($oCuslist)>0){
                    $nOk=0;$nFa=0;
                    foreach ($oCuslist as $c){
                        $sEmail=$c->Email;
                        $aEmail[]=$sEmail;
                        if(isset($c->CustomerName) && $c->CustomerName!="" && $c->CustomerName!=null){
                            $sName=$c->CustomerName;
                        }else $sName=$sEmail;
                        if($this->MailerTo($sEmail,$sName, $Subject, $Body)){
                            $nOk++;
                        }else{
                            $nFa++;
                        }
                    }
                    $this->customer_model->updateSendMail($aEmail);
                    $code=1;
                    $msg="Đã gửi thông báo Deal mới cho $nOk/$nCus khách hàng.";
                }else{
                    $code=-1;
                    $msg="Danh sách khách hàng trống. Vui lòng thử lại.";
                }
            }
            echo json_encode(array("code"=>$code,"msg"=>$msg));
        }
        
        private function CreateMailContent($list){
            $mailcontent="";
            $this->load->model('admin-planners/product_model','product_model');
            $arr= objectToArray($this->product_model->getProductInList($list));
            $mailcontent.= '
                <div style="width:600px; border:solid #09C 10px; font-family:Arial, Helvetica, sans-serif;">
                    <div style="border-bottom:solid #09C 10px; text-align:center; padding:10px 10px 10px 10px;">
                        <a href="http://dealgiadung.com/san-pham">
                            <img alt="Dealgiadung.com" src="http://dealgiadung.com/deal_css/images/logo.png" width="262" height="80" />
                        </a>
                    </div>';
            foreach ($arr as $p){
                $Image=$p["Image"];
                $UnitsOnOrder=  number_format($p["UnitsOnOrder"], 0, ',', '.');
                $UnitPrice=  number_format($p["UnitPrice"], 0, ',', '.');
                $url = base_url("san-pham/".$p["Alias"]);
                $Discount=round(($p["UnitPrice"]-$p["UnitsOnOrder"])*100/$p["UnitPrice"],0);
                $mailcontent.='
                    <div style="padding:10px 10px 10px 10px; border-bottom:solid 5px #09C;height: 150px;">
                        <table><tr><td style="width:240px;">
                        <div style="width:240px;">
                            <a href="'.$url.'" target="_blank">
                                <img alt="'.$p["ProductName"].'" style="width:240px;height:150px" src="'.$Image.'"/>
                            </a>
                        </div>
                        </td><td>
                        <div style="width:320px;padding-left:12px">
                            <a href="'.$url.'" target="_blank" style="text-decoration:none; color:#333;">
                                <div style="font-weight:bold; font-size:18px; margin-bottom:15px; padding-bottom:10px; border-bottom:thin solid #CCC;">
                                '.$p["ProductName"].'
                                </div>
                            </a>
                            <div style="margin-bottom:10px;">
                                <div style="font-weight:bold; color:#f90; font-size:30px; float:left;">'.($UnitsOnOrder).' đ</div>
                                <a href="'.$url.'" target="_blank" style="text-align:center; text-decoration:none; color:white; text-transform:uppercase; padding:10px 20px 10px 20px;">
                                    <div style="font-weight:bold; background-color:#09C; padding:3px 0px 3px 0px; font-size:20px; float:right; width:80px;">
                                        Xem
                                    </div>
                                </a>
                                <div style="clear:both;"></div>
                            </div>
                            <div style="margin-top:15px; padding-top:10px; border-top:solid #CCC thin; font-size:12px; font-weight:bold; color:#666;">
                                    <div style="float:left;">Trị giá: <span style="font-size:15px; color:#333; text-decoration:line-through;">'.($UnitPrice).' đ</span></div>
                                <div style="float:right;">Giảm: <span style="font-size:15px; color:#09C;">'.($Discount).'%</span></div>
                                <div style="clear:both;"></div>
                            </div>
                        </div>
                        </td></tr></table>
                    </div>
                ';
            }
            $mailcontent.= '</div>';
            
            return $mailcontent;
        }
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */